var fs = require('fs')
var postPath = require('../config/pathConfig').postPath
var aPageCount = require('../config/pageConfig').aPageCount
var util = require('../utility/util.js')
var Promise = require('bluebird')

var safePathCheck = util.safePathCheck

var Active = require('./activeHandler')

module.exports = {
  find: function(page, filter, callback) {
    safePathCheck(postPath, function(exists) {
      if (!exists) {
        callback(null, '没有数据')
        return
      }
      fs.readdir(postPath, function(err, files) {
        if (err) {
          console.log('postHandler find fail. err = ' + err)
          callback('获取失败')
          return
        }
        files = files.filter(function(item) {
          return item.indexOf('DS_Store') == -1
        })

        if (filter && filter.userId) {
          files = files.filter(function(item) {
            return item.indexOf(filter.userId) > -1
          })
        }

        if (files.length == 0) {
          callback(null, [])
          return
        }
        files = files.reverse()
        files = files.slice((page - 1) * aPageCount, page * aPageCount)
        var promiseAll = []
        files.map(function(file) {
          promiseAll.push(new Promise(function(resolve, reject) {
            fs.readFile(postPath + file, function(err, fileData) {
              if (err) {
                reject('读取文件失败')
              } else {
                resolve(JSON.parse(fileData))
              }
            })
          }))
        })
        Promise.all(promiseAll).then(function(resArr) {
          resArr = resArr.sort(function(obj1, obj2) {
            return new Date(obj2.updatedAt) - new Date(obj1.updatedAt)
          })
          callback(null, resArr)
        }).catch(function(err) {
          console.log('postHandler getPostList fail. err = ' + err)
          callback('获取失败')
        })
      })
    })
  },
  findById: function(id, callback, interior) {
    safePathCheck(postPath, function(exists) {
      if (exists) {
        fs.readdir(postPath, function(err, files) {
          if (err) {
            console.log('postHandler findById fail. err = ' + err)
            callback('获取失败')
            return
          }
          file = files.filter(function(fileName) {

            return fileName.slice(-21, -5) == id
          })[0]
          if (!file) {
            return callback(null, null)
          }
          var data = fs.readFileSync(postPath + file)
          var data = JSON.parse(data)
          data.readCount += 1
          var dataStr = JSON.stringify(data, null, 4)
          fs.writeFile(postPath + file, dataStr, function(err) {
            if (err) {
              console.log('postHandler findById fail. err = ' + err)
            }
            callback(null, data, interior ? file : null)
          })

        })
      } else {
        callback(null, null)
      }
    })
  },
  findByIdAndUpdate: function(id, update, callback) {
    this.findById(id, function(err, post, fileName) {
      if (err) {
        callback(err)
      } else {
        var commentId = update.commentId
        var viewPort = update.viewPort
        var handlerId = update.handlerId

        if (!viewPort) {
          //  如果没有改属性，则为收藏

          post.collectUser.push(handlerId)

        } else {
          var comments = post.comments

          outer: for (var i = 0; i < comments.length; i++) {
            var comment = comments[i]
            if (comment.id == commentId) {
              comment[viewPort].push(handlerId)
              break
            }
            var subComments = comment.comments
            for (var j = 0; j < subComments.length; j++) {
              var subComment = subComments[j]
              if (subComment.id == commentId) {
                subComment[viewPort].push(handlerId)
                break outer
              }
            }
          }
        }


        var data = JSON.stringify(post, null, 4)
        fs.writeFile(postPath + fileName, data, function(err) {
          if (err) {
            console.log('postHandler findByIdAndUpdate fail. err = ' + err)
            callback('操作失败')
          } else {
            callback(null, post)
          }
        })

      }
    }, true)
  },
  insert: function(body, callback) {
    var post = util.createPostDb(body)
    var fileName = post.handler.id + '-' + post.id + '.data'
    safePathCheck(postPath, function(exists) {
      var data = JSON.stringify(post, null, 4)
      fs.writeFile(postPath + fileName, data, function(err) {
        if (err) {
          console.log('postHandler insert fail. err = ' + err)
          callback('发表帖子失败')
        } else {

          //  发表帖子动态
          Active.insert(util.createActiveType1_2(post))

          callback(null, post)
        }
      })
    })
  }
}